<?php
/**
* $Id: tv_string_helper.php 2942 2012-02-20 10:48:18Z huong.pham $
* @author : Huong Pham  
* 
*/

/**
* Sub String with limit characters and full word. This function is better than character_limit() because we reduce the length of $text before cutting process.
*/
if (!function_exists('subStrWords')) {
    function subStrWords($text, $maxchar)
    {
        if (strlen($text) < $maxchar)
        {
            return $text;
        }
        # Replace all space with ' '
        $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
        # Reduce the length of $text to $maxchar+20 first in case the $text is too long which costs memory when storing all words to array (I think no word exceeds 20 charaters)
        if (strlen($text) > $maxchar + 20) $text = substr($text, 0, $maxchar + 20);
        # Starts cutting string
        $words = explode(" ",$text);
        $output = '';
        $i=0;
        while(1)
        {
            $length = (strlen($output)+strlen($words[$i]));
            if($length>$maxchar)
            {
                break;
            }
            else
            {
                $output = $output." ".$words[$i];
                ++$i;
            }
        }
        return $output;       
    }
}
    
if (!function_exists('getDisplayedText'))
{
    function getDisplayedText($originalString, $displayedStringLength, $start = 0)
    {
		$displayedText = $originalString;
		if (strlen($originalString) > $displayedStringLength)
		{
			$displayedText = substr($originalString, $start, $displayedStringLength) . '...';
		}
		return $displayedText;
    }
}


if (!function_exists('getRandomWord'))
{
    function getRandomWord($originalText)
    {
        $arrWords = split(', ', $originalText);
        $randIndex = array_rand($arrWords);
        return $arrWords[$randIndex];
    }
}

/* Display date of article
    author : Huong Pham
*/
if (!function_exists('displayDate'))
{
    function displayDate($dateValue)
    {
        return date('F d, Y', strtotime($dateValue));
    }
}

/**
* @desc Get total words of a string
* @param string $str
* @return int
*/
if (!function_exists('countWords')) {
    function countWords($str) {
        return count(explode(' ', $str));
    }
}

//Add  nofollow to <a>
if (!function_exists('addNoFollow'))
{
    function addNoFollow($string)
    {
        //Add rel = "nofollow" to all tag <a>
        $string = preg_replace_callback('|<a (.+?)>|i', 'nofollow_callback', $string);
        //Convert plaintext URI to HTML links.
        $string = make_clickable($string); 
        return $string;
    }
}

if(!function_exists('nofollow_callback'))
{
    function nofollow_callback( $matches ) {
        $string = $matches[1];
        $string = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $string);
        $string = str_replace(array(' rel="external"', " rel='external'"), '', $string);  
        return "<a $string rel=\"nofollow\">"; 
    }
}

/**
* Convert plaintext URI to HTML links.
*/
if(!function_exists('make_clickable'))
{
    function make_clickable($ret) 
    {
        $ret = ' ' . $ret;
        // in testing, using arrays here was found to be faster
        $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
        $ret = preg_replace_callback('#([\s>])((www|ftp|http)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
        $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
        // this one is not in an array because we need it to run last, for cleanup of accidental links within links
        $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
        $ret = trim($ret);
        return $ret;
    }   
}

/**
* Callback to convert URI match to HTML A element.
*/
if(!function_exists('_make_url_clickable_cb'))
{
    function _make_url_clickable_cb($matches) {
        $ret = '';
        $url = $matches[2];
        $url = clean_url($url);
        if ( empty($url) )
            return $matches[0];
        // removed trailing [.,;:] from URL
        if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
            $ret = substr($url, -1);
            $url = substr($url, 0, strlen($url)-1);
        }
        return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
    }    
}

/**
* Callback to convert URL match to HTML A element.
*/
if(!function_exists('_make_web_ftp_clickable_cb'))
{
    function _make_web_ftp_clickable_cb($matches) {
        $ret = '';
        $dest = $matches[2];
        $dest = 'http://' . $dest;
        $dest = clean_url($dest);
        if ( empty($dest) )
            return $matches[0];
        // removed trailing [,;:] from URL
        if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
            $ret = substr($dest, -1);
            $dest = substr($dest, 0, strlen($dest)-1);
        }
        return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
    }    
}

/**
* Callback to convert email address match to HTML A element.
*/
if(!function_exists('_make_email_clickable_cb'))
{
    function _make_email_clickable_cb($matches) 
    {
        $email = $matches[2] . '@' . $matches[3];
        return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
    }   
}

/**
* Checks and cleans a URL.
*
* A number of characters are removed from the URL. If the URL is for displaying
* (the default behaviour) amperstands are also replaced. The 'clean_url' filter
* is applied to the returned cleaned URL.
*/
if(!function_exists('clean_url'))
{
    function clean_url( $url, $protocols = null, $context = 'display' ) {
        $original_url = $url;

        if ('' == $url) return $url;
        $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$*\'()\\x80-\\xff]|i', '', $url);
        $strip = array('%0d', '%0a');
        $url = str_replace($strip, '', $url);
        $url = str_replace(';//', '://', $url);
        /* If the URL doesn't appear to contain a scheme, we
         * presume it needs http:// appended (unless a relative
         * link starting with / or a php file).
         */
        if ( strpos($url, ':') === false &&
            substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
            $url = 'http://' . $url;

        // Replace ampersands and single quotes only when displaying.
        if ( 'display' == $context ) {
            $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);
            $url = str_replace( "'", '&#039;', $url );
        }

        if ( !is_array($protocols) )
            $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
        if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
            return '';

        return $url;
    }   
}

if(!function_exists('wp_kses_bad_protocol'))
{
    function wp_kses_bad_protocol($string, $allowed_protocols) {
        $string = wp_kses_no_null($string);
        $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
        $string2 = $string.'a';

        while ($string != $string2) {
            $string2 = $string;
            $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
        } # while

        return $string;
    }   
}

/**
* Remove NULL characters in $string.  
*/

if(!function_exists('wp_kses_no_null'))
{  
    function wp_kses_no_null($string) {
        $string = preg_replace('/\0+/', '', $string);
        $string = preg_replace('/(\\\\0)+/', '', $string);

        return $string;
    }   
}

if(!function_exists('wp_kses_bad_protocol_once'))
{
    function wp_kses_bad_protocol_once($string, $allowed_protocols) {
        global $_kses_allowed_protocols;
        $_kses_allowed_protocols = $allowed_protocols;

        $string2 = preg_split('/:|&#58;|&#x3a;/i', $string, 2);
        if ( isset($string2[1]) && !preg_match('%/\?%', $string2[0]) )
            $string = wp_kses_bad_protocol_once2($string2[0]) . trim($string2[1]);
        else
            $string = preg_replace_callback('/^((&[^;]*;|[\sA-Za-z0-9])*)'.'(:|&#58;|&#[Xx]3[Aa];)\s*/', 'wp_kses_bad_protocol_once2', $string);

        return $string;
    }    
}

if(!function_exists('wp_kses_bad_protocol_once2'))
{
    function wp_kses_bad_protocol_once2($matches) {
        global $_kses_allowed_protocols;

        if ( is_array($matches) ) {
            if ( ! isset($matches[1]) || empty($matches[1]) )
                return '';

            $string = $matches[1];
        } else {
            $string = $matches;
        }

        $string2 = wp_kses_decode_entities($string);
        $string2 = preg_replace('/\s/', '', $string2);
        $string2 = wp_kses_no_null($string2);
        $string2 = preg_replace('/\xad+/', '', $string2);
        # deals with Opera "feature"
        $string2 = strtolower($string2);

        $allowed = false;
        foreach ( (array) $_kses_allowed_protocols as $one_protocol)
            if (strtolower($one_protocol) == $string2) {
                $allowed = true;
                break;
            }

        if ($allowed)
            return "$string2:";
        else
            return '';
    }   
}

if(!function_exists('wp_kses_decode_entities'))
{
    function wp_kses_decode_entities($string) {
        $string = preg_replace_callback('/&#([0-9]+);/', create_function('$match', 'return chr($match[1]);'), $string);
        $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', create_function('$match', 'return chr(hexdec($match[1]));'), $string);

        return $string;
    }   
}

if (!function_exists('addNoFollow'))
{
    function addNoFollow($string)
    {
        //Add rel = "nofollow" to all tag <a>
        $string = preg_replace_callback('|<a (.+?)>|i', 'nofollow_callback', $string);
        //Convert plaintext URI to HTML links.
        $string = make_clickable($string); 
        return $string;
    }
}
if(!function_exists('nofollow_callback'))
{
    function nofollow_callback( $matches ) {
        $string = $matches[1];
        $string = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $string);
        $string = str_replace(array(' rel="external"', " rel='external'"), '', $string);  
        return "<a $string rel=\"nofollow\">"; 
    }
}

?>